from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiTypes
from core.response import DataResponse
from report.models import Report, BodyType
from .models import Questionnaire, Question, Answer
from .serializers import QuestionnaireListSerializer, QuestionnaireDetailSerializer, QuestionnaireDuoYuanSerializer
from datetime import timedelta
from rest_framework import status
from django.utils import timezone

# Create your views here.
class QuestionnaireListAPIView(APIView):
    pagination_class = PageNumberPagination()
    def get(self, request):
        page = self.pagination_class.paginate_queryset(Questionnaire.objects.all(), request)
        serializer = QuestionnaireListSerializer(page, many=True)
        return DataResponse(serializer.data)

# $bug: 没考虑问卷版本和答案版本对不上的情况
class QuestionnaireDetailAPIView(APIView):
    def get(self, request, pk):
        questionnaire = Questionnaire.objects.get(id=pk)

        serializer = QuestionnaireDetailSerializer(questionnaire, context={'request': request})
        return DataResponse(serializer.data)

class QuestionnaireDuoYuanAPIView(APIView):
    def get(self, request):
        questionnaire = Questionnaire.objects.filter(title='多元统计分析调查2025').first()
        last_report = Report.objects.filter(
                user=request.user
            ).filter(
                created__gt=timezone.now() - timedelta(days=30)
            ).order_by('-created').first()
        if last_report is None:
            body_type = BodyType.objects.get(id=3) # 痰湿质人数最多
        else:
            body_type = BodyType.objects.get(id=last_report.body_type.id)
        serializer = QuestionnaireDuoYuanSerializer(questionnaire,
                                                    context={
                                                        'body_type': body_type,
                                                        'request': request,
                                                    })
        return DataResponse(serializer.data)

class AnswerAPIView(APIView):
    def post(self, request, pk):
        questionnaire = Questionnaire.objects.get(id=pk)
        try:
            ans = Answer.objects.get(questionnaire=questionnaire, user=request.user)
        except Answer.DoesNotExist:
            answers = request.data.get('answers')
            version = request.data.get('version')
            Answer.objects.create(questionnaire=questionnaire,
                                questionnaire_version=version,
                                user=request.user,
                                answers=answers,
                                )
            return DataResponse(code=200, message="提交成功")
        return DataResponse(code=401, message="已经提交过答案", status=status.HTTP_401_UNAUTHORIZED)
